package com.fjwt.gz.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjwt.gz.components.mq.websocket.server.PCWsChannelServer;
import com.fjwt.gz.components.oss.model.MockMultipartFile;
import com.fjwt.gz.components.oss.model.OssFileConfig;
import com.fjwt.gz.components.oss.service.OssFileService;
import com.fjwt.gz.core.cache.RedisUtil;
import com.fjwt.gz.core.constants.CS;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.model.security.GzUserDetails;
import com.fjwt.gz.db.dto.AgentEmployeeDTO;
import com.fjwt.gz.db.entity.*;
import com.fjwt.gz.db.vo.AgentEmployeeExportVO;
import com.fjwt.gz.db.vo.AgentEmployeeVO;
import com.fjwt.gz.service.mapper.AgentEmployeeMapper;
import com.fjwt.gz.service.mapper.AgentInfoMapper;
import com.fjwt.gz.service.mapper.FansAgentMapper;
import com.fjwt.gz.service.mapper.FansUserMapper;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 机构员工表 服务实现类
 * </p>
 *
 * @author shiyonghao
 * @since 2025-04-09
 */
@Slf4j
@Service
public class AgentEmployeeService extends ServiceImpl<AgentEmployeeMapper, AgentEmployeeEntity> {
    @Autowired
    private AgentEmployeeMapper agentEmployeeMapper;
    @Autowired
    private AgentInfoService agentInfoService;

    @Autowired
    private OssRecordService ossRecordService;

    @Autowired
    private OssFileService ossFileService;
    @Autowired
    private AgentInfoMapper agentInfoMapper;
    @Autowired
    private FansAgentMapper fansAgentMapper;
    @Autowired
    private FansAgentService fansAgentService;
    @Autowired
    private FansService fansService;
    @Autowired
    private FansUserMapper fansUserMapper;

    @Autowired
    private PCWsChannelServer wsChannelServer;

    /**
     * 机构员工列表
     * @param page
     * @param agentEmployeeDTO
     * @return
     */
    public IPage<AgentEmployeeVO> queryList(IPage page, AgentEmployeeDTO agentEmployeeDTO) {
        if (null !=agentEmployeeDTO.getCurrentAgentNo() && !"0".equals(agentEmployeeDTO.getCurrentAgentNo())){
            agentEmployeeDTO.setAgentNos(agentInfoService.queryAllSubAgentNo(agentEmployeeDTO.getCurrentAgentNo()));
        }
        IPage<AgentEmployeeVO> pages =   agentEmployeeMapper.selectAgentEmployeeList(page,agentEmployeeDTO);

        // 查询路径层级
        Map<String, String> agentNameMap = new HashMap<>();
        if (ObjectUtils.isNotEmpty(pages) && ObjectUtils.isNotEmpty(pages.getRecords())) {
            //手机号脱敏
            pages.convert(e -> {
                e.setEmployeePhone(DesensitizedUtil.mobilePhone(e.getEmployeePhone()));
                return e;
            });
            Set<String> agentNos = pages.getRecords().stream().flatMap(item ->
                            Stream.of(item.getAgentNo1(), item.getAgentNo2(), item.getAgentNo3(), item.getAgentNo4()))
                    .filter(Objects::nonNull).collect(Collectors.toSet());
            if (ObjectUtils.isNotEmpty(agentNos)) {
                List<AgentInfoEntity> agentInfoList = agentInfoMapper.selectBatchIds(agentNos);
                if (ObjectUtils.isNotEmpty(agentInfoList)) {
                    agentNameMap = agentInfoList.stream().collect(Collectors.toMap(AgentInfoEntity::getAgentNo, AgentInfoEntity::getAgentName));
                }
            }
        }

        for (AgentEmployeeVO record : pages.getRecords()) {
            record.setHierarchyPath(getHierarchyPath(record, agentNameMap));
            //添加是否有展业权限  根据是否有appid fansAgent中只保留一个，根据对应的机构人员id
            record.setBusinessPermission(record.getIsDeleted() != null && record.getIsDeleted() == 0 ? 1 : 0);
        }
        return pages;
    }


    /**
     * 获取机构层级路径
     *
     * @param agentInfoVO
     * @return
     */
    private String getHierarchyPath(AgentEmployeeVO agentInfoVO, Map<String, String> agentNameMap) {
        StringBuilder hierarchyPath = new StringBuilder();

        if (agentNameMap.containsKey(agentInfoVO.getAgentNo1())) {
            if (!hierarchyPath.isEmpty()) {
                hierarchyPath.append("-");
            }
            hierarchyPath.append(agentNameMap.get(agentInfoVO.getAgentNo1()));
        }
        if (agentNameMap.containsKey(agentInfoVO.getAgentNo2())) {
            if (!hierarchyPath.isEmpty()) {
                hierarchyPath.append("-");
            }
            hierarchyPath.append(agentNameMap.get(agentInfoVO.getAgentNo2()));
        }
        if (agentNameMap.containsKey(agentInfoVO.getAgentNo3())) {
            if (!hierarchyPath.isEmpty()) {
                hierarchyPath.append("-");
            }
            hierarchyPath.append(agentNameMap.get(agentInfoVO.getAgentNo3()));
        }
        if (agentNameMap.containsKey(agentInfoVO.getAgentNo4())) {
            if (!hierarchyPath.isEmpty()) {
                hierarchyPath.append("-");
            }
            hierarchyPath.append(agentNameMap.get(agentInfoVO.getAgentNo4()));
        }
        return hierarchyPath.toString();
    }

    /**
     * 批量增加机构员工
     * @param bizType
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String addByBatch(AgentEmployeeDTO agentEmployeeDTO, String bizType) {
        List<AgentEmployeeEntity> agentEmployeeEntityList =null;
        //运营端和机构端判断
        if (!"0".equals(agentEmployeeDTO.getCurrentAgentNo())){
            //查询当前机构和下级所有机构人员
            agentEmployeeDTO.setAgentNos(agentInfoService.queryAllSubAgentNo(agentEmployeeDTO.getCurrentAgentNo()));
            agentEmployeeEntityList = agentEmployeeMapper.selectList(AgentEmployeeEntity.gw()
                    .select(AgentEmployeeEntity::getAgentNo, AgentEmployeeEntity::getEmployeeNo)
                    .in(ObjectUtils.isNotEmpty(agentEmployeeDTO.getAgentNos()),  AgentEmployeeEntity::getAgentNo, agentEmployeeDTO.getAgentNos()));
        }else {
            //查询数据库中所有机构人员
            agentEmployeeEntityList = agentEmployeeMapper.selectList(AgentEmployeeEntity.gw().select(AgentEmployeeEntity::getAgentNo, AgentEmployeeEntity::getEmployeeNo));
        }
        // 获取文件导入的渠道信息
        List<AgentEmployeeEntity> agentEmployeeToList = this.getAgentEmployeeEntityToList(agentEmployeeDTO.getOssFileUrl(), bizType);
        log.info("新增渠道码 新增数据：{}, 批量机构员工导入文件数据：{}", JSONUtil.toJsonStr(agentEmployeeToList), JSONUtil.toJsonStr(agentEmployeeToList));
        // 结果数据
        List<JSONObject> resultJsonList = new ArrayList<>();
        if (!agentEmployeeToList.isEmpty()){
            Set<AgentEmployeeEntity> addSet = new HashSet<>();
            for (int i = 0; i < agentEmployeeToList.size(); i++) {
                AgentEmployeeEntity item = agentEmployeeToList.get(i);
                Integer total = agentEmployeeToList.size();
                JSONObject json = new JSONObject();
                if (ObjectUtils.isEmpty(item.getEmployeeName())){
                    resultJson(item, json,resultJsonList,"员工姓名不能为空");
//                    wsChannelServer.convertAndSend(String.valueOf(GzUserDetails.getCurrentUserDetails().getSysUserId()), total, "导入机构员工", "第" + (i + 1) + "行，员工姓名不能为空！", WebSocketConstants.ImportStatus.FAIL);
                    continue;
                }
                if (ObjectUtils.isEmpty(item.getEmployeeNo())){
                    resultJson(item, json, resultJsonList,"员工编号不能为空");
//                    wsChannelServer.convertAndSend(String.valueOf(GzUserDetails.getCurrentUserDetails().getSysUserId()), total, "导入机构员工", "第" + (i + 1) + "行，员工编号不能为空！", WebSocketConstants.ImportStatus.FAIL);
                    continue;
                }
                if (ObjectUtils.isEmpty(item.getAgentNo())){
                    resultJson(item, json, resultJsonList,"机构号不能为空");
//                    wsChannelServer.convertAndSend(String.valueOf(GzUserDetails.getCurrentUserDetails().getSysUserId()), total, "导入机构员工", "第" + (i + 1) + "行，机构号不能为空！", WebSocketConstants.ImportStatus.FAIL);
                    continue;
                }
                if (ObjectUtils.isEmpty(item.getEmployeePhone())){
                    resultJson(item, json, resultJsonList,"机构人员手机号不能为空");
//                    wsChannelServer.convertAndSend(String.valueOf(GzUserDetails.getCurrentUserDetails().getSysUserId()), total, "导入机构员工", "第" + (i + 1) + "行，机构人员手机号不能为空！", WebSocketConstants.ImportStatus.FAIL);
                    continue;
                }
                //手机号正则表达式校验
                String phoneRegex="^1[3-9]\\d{9}$";
                if (!item.getEmployeePhone().matches(phoneRegex)){
                    resultJson(item, json, resultJsonList,"手机号格式不正确");
//                    wsChannelServer.convertAndSend(String.valueOf(GzUserDetails.getCurrentUserDetails().getSysUserId()), total, "导入机构员工", "第" + (i + 1) + "行，手机号格式不正确！", WebSocketConstants.ImportStatus.FAIL);
                    continue;
                }
                //判断agentEmployeeEntityList中是否包含相同的getEmployeeNo和getEmployeeName
                boolean flag = agentEmployeeEntityList.stream().anyMatch(e ->
                        Objects.equals(e.getEmployeeNo(), item.getEmployeeNo()) && Objects.equals(e.getAgentNo(), item.getAgentNo())
                );
                //机构端和运营端判断条件
                if (StringUtils.isNotEmpty(agentEmployeeDTO.getCurrentAgentNo())){
                    if ( ObjectUtils.isNotEmpty(agentEmployeeDTO.getAgentNos()) && !agentEmployeeDTO.getAgentNos().contains(item.getAgentNo())) {
                        resultJson(item, json, resultJsonList, "该人员不属于此机构或下级机构");
//                        wsChannelServer.convertAndSend(String.valueOf(GzUserDetails.getCurrentUserDetails().getSysUserId()), total, "导入机构员工", "第" + (i + 1) + "行，该人员不属于此机构或下级机构！", WebSocketConstants.ImportStatus.FAIL);
                        continue;
                    }
                }
                if (flag) {
                    resultJson(item,  json,resultJsonList,"机构下已存在该员工");
//                    wsChannelServer.convertAndSend(String.valueOf(GzUserDetails.getCurrentUserDetails().getSysUserId()), total, "导入机构员工", "第" + (i + 1) + "行，机构下已存在该员工！", WebSocketConstants.ImportStatus.FAIL);
                    continue;
                }
                AgentInfoEntity agentInfo = agentInfoService.getAgentInfo(item.getAgentNo());
                if (ObjectUtils.isEmpty(agentInfo)){
                    resultJson(item, json, resultJsonList,"所选机构不存在，请检查！");
//                    wsChannelServer.convertAndSend(String.valueOf(GzUserDetails.getCurrentUserDetails().getSysUserId()), total, "导入机构员工", "第" + (i + 1) + "行，所选机构不存在，请检查！", WebSocketConstants.ImportStatus.FAIL);
                    continue;
                }
                item.setAgentNo1(agentInfo.getAgentNo1());
                item.setAgentNo2(agentInfo.getAgentNo2());
                item.setAgentNo3(agentInfo.getAgentNo3());
                item.setAgentNo4(agentInfo.getAgentNo4());

//                wsChannelServer.convertAndSend(String.valueOf(GzUserDetails.getCurrentUserDetails().getSysUserId()), total, "导入机构员工", "导入成功！", WebSocketConstants.ImportStatus.SUCCESS);
                addSet.add(item);
            }
            if (ObjectUtils.isNotEmpty(addSet)) {
                saveBatch(addSet);
            }
        }
        if (ObjectUtils.isNotEmpty(resultJsonList)) {
            return importEmployeeFailUrl(resultJsonList);
        }
        return "success";
    }
    //封装返回结果
    private static void resultJson(AgentEmployeeEntity item, JSONObject json,List<JSONObject> resultJsonList,String failReason) {
        json.put("employeeNo", item.getEmployeeNo());
        json.put("employeeName",  item.getEmployeeName());
        json.put("agentNo", item.getAgentNo());
        json.put("remark",  item.getRemark());
        json.put("employeePhone", item.getEmployeePhone());
        json.put("failReason", failReason);
        resultJsonList.add(json);
    }


    /**
     * 导出失败员工数据
     */
    private String importEmployeeFailUrl(List<JSONObject> failList) {
        String failUrl = null;
        if (ObjectUtils.isEmpty(failList)){
            return null;
        }
        //将failSet导出
        String failFileName = String.format("./temp/addBatch/fail/%s.xlsx", DateUtil.date().getTime());
        File normalFile = new File(failFileName);
        ExcelWriter failWriter = ExcelUtil.getWriter(normalFile);
        failWriter.addHeaderAlias("employeeNo","员工编号");
        failWriter.addHeaderAlias("employeeName","员工姓名");
        failWriter.addHeaderAlias("agentNo","归属机构");
        failWriter.addHeaderAlias("remark","备注");
        failWriter.addHeaderAlias("employeePhone","手机号");
        failWriter.addHeaderAlias("failReason","失败原因");
        try {
            failWriter.write(failList);
            failWriter.close();
            MultipartFile multipartFile = new MockMultipartFile(failFileName, normalFile.length(), new FileInputStream(normalFile));
            failUrl = ossFileService.singleFileUpload(multipartFile, OssFileConfig.BIZ_TYPE.DOWNLOAD);
            // 添加oos上传记录
            OssRecordEntity ossRecordEntity = new OssRecordEntity();
            ossRecordEntity.setBizType(OssFileConfig.BIZ_TYPE.DOWNLOAD);
            ossRecordEntity.setOssUrl(failUrl);
            ossRecordEntity.setFileSize(normalFile.length());
            ossRecordEntity.setUploadType(Constants.OSS_UPLOAD_TYPE.AGENT_EMPLOYEE_IMPORT_FAIL);
            ossRecordEntity.setCreatedAt(new Date());
            ossRecordService.save(ossRecordEntity);
            FileUtil.del(normalFile);
        } catch (Exception e) {
            throw new BizException(e.getMessage());
        }
        return failUrl;
    }

    /**
     * oss文件导入渠道
     * @return
     */
    public List<AgentEmployeeEntity> getAgentEmployeeEntityToList(String ossFileUrl, String bizType){
        File file= FileUtil.file(String.format("./temp/%s.xlsx", DateUtil.date().getTime()));
        HttpUtil.downloadFile(ossFileUrl, file);

        LambdaQueryWrapper<OssRecordEntity> ossRecordWrapper = new LambdaQueryWrapper<>();
        ossRecordWrapper.eq(OssRecordEntity::getOssUrl,ossFileUrl);
        ossRecordWrapper.eq(OssRecordEntity::getUploadType, Constants.OSS_UPLOAD_TYPE.ACTIVITY_CHANNEL_IMPORT);
        OssRecordEntity recordEntity = ossRecordService.getBaseMapper().selectOne(ossRecordWrapper);
        if(null == recordEntity ){
            // 添加oos上传记录
            OssRecordEntity ossRecordEntity = new OssRecordEntity();
            ossRecordEntity.setBizType(bizType);
            ossRecordEntity.setOssUrl(ossFileUrl);
            ossRecordEntity.setFileSize(file.length());
            ossRecordEntity.setUploadType(Constants.OSS_UPLOAD_TYPE.ACTIVITY_CHANNEL_IMPORT);
            ossRecordEntity.setSysUserId(GzUserDetails.getCurrentUserDetails().getSysUser().getSysUserId());
            ossRecordEntity.setCreatedAt(new Date());
            ossRecordService.save(ossRecordEntity);
        }else{
            OssRecordEntity ossRecordEntity = new OssRecordEntity();
            ossRecordEntity.setOssRecordId(recordEntity.getOssRecordId());
            ossRecordEntity.setOssUrl(ossFileUrl);
            ossRecordService.getBaseMapper().updateById(ossRecordEntity);
        }
        // 读取文件内容
        ExcelReader reader = ExcelUtil.getReader(file);

        reader.addHeaderAlias("员工编号","employeeNo");
        reader.addHeaderAlias("员工姓名","employeeName");
        reader.addHeaderAlias("归属机构","agentNo");
        reader.addHeaderAlias("备注","remark");
        reader.addHeaderAlias("手机号","employeePhone");
        List<AgentEmployeeEntity> all = reader.readAll(AgentEmployeeEntity.class);
        reader.close();
        FileUtil.del(file);
        return all;
    }

    /**
     * 查询单个机构人员信息
     * @param agentNo 机构号
     * @return
     */
    public AgentEmployeeEntity getAgentEmployeeInfo(String agentNo, String employeeNo) {
        // 查缓存
        String cacheKeyAgentInfo = CS.getCacheKeyAgentEmployee(agentNo, employeeNo);
        AgentEmployeeEntity agentEmployeeEntity = RedisUtil.getObject(cacheKeyAgentInfo, AgentEmployeeEntity.class);
        // 缓存为空查数据库
        if (ObjectUtils.isEmpty(agentEmployeeEntity)) {
            LambdaQueryWrapper<AgentEmployeeEntity> employeeWrapper = AgentEmployeeEntity.gw();
            employeeWrapper.eq(AgentEmployeeEntity::getEmployeeNo, employeeNo);
            employeeWrapper.eq(AgentEmployeeEntity::getAgentNo, agentNo);
            agentEmployeeEntity = agentEmployeeMapper.selectOne(employeeWrapper);
            // 数据库存在放入缓存
            if (ObjectUtils.isNotEmpty(agentEmployeeEntity)) {
                RedisUtil.set(cacheKeyAgentInfo, agentEmployeeEntity);
            }
        }
        return agentEmployeeEntity;
    }

    public JSONObject export(IPage<AgentEmployeeVO> page, HttpServletResponse response){
        ArrayList<AgentEmployeeExportVO> agentInfoExportVOS = new ArrayList<>();
        for (AgentEmployeeVO agentEmployeeVO : page.getRecords()) {
            AgentEmployeeExportVO agentEmployeeExportVO = new AgentEmployeeExportVO();
            BeanUtils.copyProperties(agentEmployeeVO, agentEmployeeExportVO);
            agentInfoExportVOS.add(agentEmployeeExportVO);
        }

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=exportedData.xlsx");

        String successFileName = String.format("./agentInfo/employee/%s.xlsx","机构人员信息" + DateUtil.date().getTime());

        File successFile = new File(successFileName);
        BigExcelWriter writer = ExcelUtil.getBigWriter(successFile);

        writer.renameSheet("机构人员信息导出");
        writer.addHeaderAlias("fansId", "用户id");
        writer.addHeaderAlias("employeeNo", "员工编号");
        writer.addHeaderAlias("employeeName", "员工姓名");
        writer.addHeaderAlias("businessPermission", "是否有展业权限【0否 1是】");
        writer.addHeaderAlias("agentNo", "机构号");
        writer.addHeaderAlias("agentNo1", "一级机构号");
        writer.addHeaderAlias("agentNo2", "二级机构号");
        writer.addHeaderAlias("agentNo3", "三级机构号");
        writer.addHeaderAlias("agentNo4", "四级机构号");
        writer.addHeaderAlias("hierarchyPath", "归属层级路径");
        writer.addHeaderAlias("createdAt", "创建时间");
        writer.addHeaderAlias("updatedAt", "更新时间");
        writer.setOnlyAlias(true);
        writer.write(agentInfoExportVOS);
        writer.autoSizeColumnAll();
        // 关闭writer，释放资源
        writer.close();
        try {
            MultipartFile multipartFile = new MockMultipartFile(successFileName, successFile.length(), new FileInputStream(successFile));
            String successUrl = ossFileService.singleFileUpload(multipartFile, OssFileConfig.BIZ_TYPE.UPLOAD);
            // 添加oos上传记录
            OssRecordEntity ossRecordEntity = new OssRecordEntity();
            ossRecordEntity.setBizType("scorexq");
            ossRecordEntity.setOssUrl(successUrl);
            ossRecordEntity.setFileSize(successFile.length());
            ossRecordEntity.setUploadType(Constants.OSS_UPLOAD_TYPE.AGENT_INFO_IMPORT);
            ossRecordEntity.setCreatedAt(new Date());
            ossRecordService.save(ossRecordEntity);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("successUrl", successUrl);
            //删除文件
            FileUtil.del(successFile);
            return jsonObject;
        } catch (Exception e) {
            throw new BizException(e.getMessage());
        }
    }


    public void bindBusinessPermission(Long agentEmployeeId,String appId,Integer isBind,String payOpenId){
        if (ObjectUtils.isEmpty(agentEmployeeId)) {
            throw new BizException("机构员工Id不能为空");
        }
        if (StringUtils.isBlank(appId)) {
            throw new BizException("小程序appid不能为空");
        }
        if (ObjectUtils.isEmpty(isBind)) {
            throw new BizException("是否绑定不能为空");
        }
        if (StringUtils.isBlank(payOpenId)) {
            throw new BizException("微信Id不能为空");
        }
        //查询当前小程序下是否绑定成功
        AgentEmployeeEntity agentEmployeeEntity = agentEmployeeMapper.selectById(agentEmployeeId);
        if (ObjectUtils.isEmpty(agentEmployeeEntity)) {
            throw new BizException("机构员工信息为空");
        }
        LambdaQueryWrapper<FansAgentEntity> fansAgentGw = FansAgentEntity.gw();
        fansAgentGw.eq(FansAgentEntity::getAgentEmployeeId,agentEmployeeId);
        fansAgentGw.eq(FansAgentEntity::getAppId,appId);
        FansAgentEntity fansAgentEntity = fansAgentMapper.selectOne(fansAgentGw);
        if (1==isBind){
            //解绑
            if (ObjectUtils.isEmpty(fansAgentEntity)) {
                throw new BizException("该机构人员在此小程序下没有展业权限");
            }
            if (fansAgentEntity.getIsDeleted() == 1){
                throw new BizException("该机构员工在小程序下已经解绑");
            }
            fansAgentEntity.setIsDeleted(1);
            fansAgentMapper.updateById(fansAgentEntity);
            //清除客户经理规则下的缓存
            //blacklistService.deleteBlacklistCache();
        }else {
            //判断机构用户是否存在，且绑定状态为绑定，则不可重复绑定
            if (ObjectUtils.isNotEmpty(fansAgentEntity) && fansAgentEntity.getIsDeleted() == 0) {
                throw new BizException("该机构人员在此小程序下已有展业权限,不可重复绑定");
            }
            //查询用户在此小程序是否登录过
            LambdaQueryWrapper<FansEntity> fansGw = FansEntity.gw();
            fansGw.eq(FansEntity::getPayOpenId,payOpenId);
            FansEntity fans = fansService.getOne(fansGw);
            if (ObjectUtils.isEmpty(fans)) {
                throw new BizException("该机构人员未登录任何小程序");
            }
            LambdaQueryWrapper<FansUserEntity> fansUserGw = FansUserEntity.gw();
            fansUserGw.eq(FansUserEntity::getFansId,fans.getFansId());
            fansUserGw.eq(FansUserEntity::getAppId,appId);
            fansUserGw.eq(FansUserEntity::getType,1);
            FansUserEntity fansUserEntity = fansUserMapper.selectOne(fansUserGw);
            if (ObjectUtils.isEmpty(fansUserEntity)) {
                throw new BizException("该机构人员在此小程序下未登录");
            }
            if (fansUserEntity.getState() == 1 || fansUserEntity.getState() == 2) {
                throw new BizException("该机构人员在此小程序下的登录状态为已注销");
            }

            //机构人员fansAgent不存在，或者绑定状态为未绑定，需要把此机构号所有的fansAgent记录全置为未绑定，最后绑定传过来的数据
            LambdaQueryWrapper<AgentEmployeeEntity> gw = AgentEmployeeEntity.gw();
            gw.eq(AgentEmployeeEntity::getEmployeeNo,agentEmployeeEntity.getEmployeeNo());
            List<AgentEmployeeEntity> agentEmployeeEntities = agentEmployeeMapper.selectList(gw);
            for (AgentEmployeeEntity entity : agentEmployeeEntities) {
                fansAgentService.lambdaUpdate()
                        .eq(FansAgentEntity::getAgentEmployeeId,entity.getAgentEmployeeId())
                        .set(FansAgentEntity::getIsDeleted, 1)
                        .update();
            }
            fansAgentService.lambdaUpdate()
                    .eq(FansAgentEntity::getAppId,appId)
                    .eq(FansAgentEntity::getIsDeleted, 0)
                    .eq(FansAgentEntity::getFansId, fans.getFansId())
                    .set(FansAgentEntity::getIsDeleted, 1)
                    .update();

            if (ObjectUtils.isEmpty(fansAgentEntity)) {
                //新增
                FansAgentEntity fansAgent = new FansAgentEntity();
                fansAgent.setIsDeleted(0);
                fansAgent.setAgentEmployeeId(agentEmployeeId);
                fansAgent.setFansId(fans.getFansId());
                fansAgent.setAppId(appId);
                fansAgent.setCreatedAt(new Date());
                fansAgent.setUpdateAt(new Date());
                fansAgentService.save(fansAgent);
            }else {
                //修改状态
                fansAgentEntity.setIsDeleted(0);
                fansAgentEntity.setUpdateAt(new Date());
                fansAgentService.updateById(fansAgentEntity);
            }
            //清除客户经理规则下的缓存
//            blacklistService.deleteBlacklistCache();
        }
    }

    /**
     * 根据机构号获取员工列表
     * @param dto
     * @return
     */
    public List<AgentEmployeeEntity> getListByAgentNo(AgentEmployeeDTO dto) {
        return list(AgentEmployeeEntity.gw()
                .eq(AgentEmployeeEntity::getAgentNo, dto.getAgentNo()));
    }
}
